import { sysMenus } from "@/types/apiTypes";
import { RouteRecordRaw } from "vue-router";
import router from "@/router/index.ts";
// import Layout from "@/views/layout/vehicleMaintain.vue";

const routerComponents = import.meta.glob("@/views/**/*.vue");

function getComponents(component: string) {
  // if (component === "layout/layout") {
  //   return Layout;
  // }
  return routerComponents[`/src/views/${component}.vue`];
}

export function formatRouter(routes: sysMenus[]) {
  const userRoutes: RouteRecordRaw[] = [];
  routes?.forEach((menu) => {
    const { id, menuUrl, menuName, menuCode, menuIcon, children, component } =
      menu;

    const router: RouteRecordRaw = {
      path: menuUrl,
      name: menuCode,
      component: getComponents(component),
      children: formatRouter(children),
      meta: {
        id,
        title: menuName,
        icon: menuIcon,
        hide: true,
      },
    };
    userRoutes.push(router);
  });
  return userRoutes;
}

export async function addUserRouter(userMenus: sysMenus[]) {
  const userRouter = formatRouter(userMenus);

  userRouter?.forEach((item) => {
    router.addRoute("main", item);
  });
  return Promise.resolve();
}
